package com.heima.search.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class ApAssociateWordsServiceimpl implements ApAssociateWordsService {

    @Resource
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult findAssociate(UserSearchDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //联想查询
        List<ApAssociateWords> apAssociateWordsList = mongoTemplate.find(Query.query(Criteria.where("associateWords").regex(".*" + dto.getSearchWords() + ".*")), ApAssociateWords.class);


        //返回结果
        return ResponseResult.okResult(apAssociateWordsList);
    }
}
